/*
 * @Description: 消息详情   DetailsMessage
 * @version: 
 * @Company: 
 * @Author: ZhengZhuang
 * @Date: 2019-08-27 09:48:23
 * @LastEditors: zhengzhuang
 * @LastEditTime: 2020-11-18 09:19:49
 */
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:C20Driver/config/service_api.dart';
import 'package:C20Driver/model/get_chat_content.dart';
import 'package:C20Driver/service/service_method.dart';
import 'package:C20Driver/widget/appbar_widget.dart';

/// 聊天界面示例
class DetailsMessage extends StatefulWidget {
  final String orderId;
  final String userName;
  DetailsMessage({this.orderId, this.userName});
  @override
  DetailsMessageState createState() {
    return DetailsMessageState();
  }
}

class DetailsMessageState extends State<DetailsMessage>
    with AutomaticKeepAliveClientMixin {
  // 信息列表
  List _msgList;

  // 输入框
  TextEditingController _textEditingController;

  // 滚动控制器
  ScrollController _scrollController;

  FocusNode _focusNode = new FocusNode();

  // 快速发送消息列表显示状态
  bool quickMessageListState = false;

  @override
  void initState() {
    super.initState();

    _textEditingController = TextEditingController();
    _textEditingController.addListener(() {
      setState(() {});
    });
    _scrollController = ScrollController();
    _focusNode.addListener(_focusNodeListener);
  }

  Future<Null> _focusNodeListener() async {
    if (_focusNode.hasFocus) {
      print('获取焦点');
      setState(() {
        quickMessageListState = false;
      });
    } else {
      print('失去焦点');
    }
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    _scrollController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  // 发送消息
  void _sendMsg(_msgListData, String msg) {
    print('发送消息发送消息发送消息发送消息发送消息发送消息');
    print(GetChatContent.fromJson({
      "id": "1142896818959569666",
      "from_id": "1142889689825594113",
      "to_id": "1298582573957549824",
      "content": msg,
      "create_time": "2019-10-16 09:51:00",
      "order_id": "1143222174165766145",
      "position": "1",
      "user_name": "乘客一",
      "headimgurl":
          "http://thirdwx.qlogo.cn/mmopen/Q3auHgzwzM5exwtRCGRFPicEJXHAbYic8gBwkb87NjFqiaBIzcsGo1a8DGng3xJeqWWqqWd8AtNwzXveW390SsZjQ/132"
    }));
    print(_msgList.toString());
    setState(() {
      _msgList.insert(0, {
        "id": "1142896818959569666",
        "from_id": "1142889689825594113",
        "to_id": "1298582573957549824",
        "content": msg,
        "create_time": "2019-10-16 09:51:00",
        "order_id": "1143222174165766145",
        "position": "1",
        "user_name": "乘客一",
        "headimgurl":
            "http://thirdwx.qlogo.cn/mmopen/Q3auHgzwzM5exwtRCGRFPicEJXHAbYic8gBwkb87NjFqiaBIzcsGo1a8DGng3xJeqWWqqWd8AtNwzXveW390SsZjQ/132"
      });
    });
    _scrollController.animateTo(
      0.0,
      duration: Duration(milliseconds: 300),
      curve: Curves.linear,
    );
  }

  int page = 1;
  // 获取消息内容列表
  Future<void> getChatContentFun() async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.getChatContent, params: {
      'page': page.toString(),
      'pageSize': '10',
      'order_id': widget.orderId,
    }, success: (res) async {
      return res;
    });
  }

  @override
  Widget build(BuildContext context) {
    //白色
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // 触摸空白处收起键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        appBar: AppbarWidget(
          widget.userName,
          color: Colors.white,
        ),
        backgroundColor: Colors.grey[200],
        body: Column(
          children: <Widget>[
            Divider(height: ScreenUtil().setHeight(1.0)),
            Expanded(
              flex: 1,
              child: FutureBuilder(
                future: getChatContentFun(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  _msgList = snapshot.data;
                  // setState(() {
                  //   _msgList = snapshot.data;
                  // });
                  // List _msgList = snapshot.data;
                  if (snapshot.hasData && _msgList != null) {
                    return EasyRefresh.custom(
                      scrollController: _scrollController,
                      reverse: true,
                      footer: CustomFooter(
                        enableInfiniteLoad: false,
                        extent: 40.0,
                        triggerDistance: 50.0,
                        footerBuilder: (context,
                            loadState,
                            pulledExtent,
                            loadTriggerPullDistance,
                            loadIndicatorExtent,
                            axisDirection,
                            float,
                            completeDuration,
                            enableInfiniteLoad,
                            success,
                            noMore) {
                          return Stack(
                            children: <Widget>[
                              Positioned(
                                bottom: 0.0,
                                left: 0.0,
                                right: 0.0,
                                child: Container(
                                  width: ScreenUtil().setWidth(60.0),
                                  height: ScreenUtil().setWidth(60.0),
                                  child: SpinKitCircle(
                                    color: Colors.green,
                                    size: ScreenUtil().setWidth(60.0),
                                  ),
                                ),
                              ),
                            ],
                          );
                        },
                      ),
                      slivers: <Widget>[
                        SliverList(
                          delegate: SliverChildBuilderDelegate(
                              (context, index) {
                            return _buildMsg(
                                GetChatContent.fromJson(_msgList[index]));
                            // return Text('data');
                          },
                              childCount: _msgList.length,
                              addRepaintBoundaries: false),
                        ),
                      ],
                      onLoad: () async {
                        await Future.delayed(Duration(seconds: 2), () {
                          setState(() {
                            _msgList.addAll([
                              // MessageEntity(true, "It's good!"),
                              // MessageEntity(false, 'EasyRefresh'),
                            ]);
                          });
                        });
                      },
                    );
                  } else {
                    return Container();
                  }
                },
              ),
            ),
            Container(
              padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(30.0),
                right: ScreenUtil().setWidth(30.0),
                top: ScreenUtil().setWidth(16.0),
                bottom: ScreenUtil().setWidth(16.0),
              ),
              color: Colors.grey[100],
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: Container(
                          padding: EdgeInsets.all(ScreenUtil().setWidth(10.0)),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.all(Radius.circular(
                              4.0,
                            )),
                          ),
                          child: TextField(
                            controller: _textEditingController,
                            focusNode: _focusNode,
                            decoration: InputDecoration(
                              contentPadding: EdgeInsets.only(
                                top: 2.0,
                                bottom: 2.0,
                              ),
                              border: InputBorder.none,
                            ),
                            onSubmitted: (value) {
                              if (_textEditingController.text.isNotEmpty) {
                                _sendMsg(_msgList, _textEditingController.text);
                                _textEditingController.text = '';
                              }
                            },
                          ),
                        ),
                      ),

                      /// 发送位置按钮
                      _sendLocationButton(),
                    ],
                  ),
                  Offstage(
                    offstage: !quickMessageListState,
                    child: Container(
                      width: ScreenUtil().setWidth(750.0),
                      height: ScreenUtil().setWidth(400.0),
                      child: ListView(
                        children: <Widget>[
                          _quickMessageList('您好，我正前往，请问您的导航位置准确吗?'),
                          _quickMessageList('您好，请稍等'),
                          _quickMessageList('我正在路上，马上就到达'),
                          _quickMessageList('我马上就到，请您稍等一下'),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 发送位置按钮
  Widget _sendLocationButton() {
    return Container(
      height: ScreenUtil().setWidth(60.0),
      width: ScreenUtil().setWidth(120.0),
      alignment: Alignment.center,
      child: Stack(
        children: <Widget>[
          Offstage(
            offstage: _textEditingController.text.isEmpty,
            child: InkWell(
              onTap: () {
                if (_textEditingController.text.isNotEmpty) {
                  _sendMsg(_msgList, _textEditingController.text);
                  _textEditingController.text = '';
                }
              },
              child: Container(
                height: ScreenUtil().setWidth(60.0),
                width: ScreenUtil().setWidth(120.0),
                alignment: Alignment.center,
                margin: EdgeInsets.only(
                  left: ScreenUtil().setWidth(30.0),
                ),
                decoration: BoxDecoration(
                  color: _textEditingController.text.isEmpty
                      ? Colors.grey
                      : Colors.green,
                  borderRadius: BorderRadius.all(Radius.circular(
                    4.0,
                  )),
                ),
                child: Text(
                  "发送",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: ScreenUtil().setSp(16.0),
                  ),
                ),
              ),
            ),
          ),
          Offstage(
            offstage: !(_textEditingController.text.isEmpty),
            child: Stack(
              children: <Widget>[
                Offstage(
                  offstage: quickMessageListState,
                  child: InkWell(
                    child: Container(
                      height: ScreenUtil().setWidth(60.0),
                      width: ScreenUtil().setWidth(120.0),
                      child: Image.asset(
                        'assets/icon/keyboardButtonIcon.png',
                        width: ScreenUtil().setWidth(50.0),
                        height: ScreenUtil().setWidth(50.0),
                      ),
                    ),
                    onTap: () {
                      _focusNode.unfocus(); // 失去焦点
                      setState(() {
                        quickMessageListState = true;
                      });
                    },
                  ),
                ),
                Offstage(
                  offstage: !quickMessageListState,
                  child: InkWell(
                    child: Container(
                      height: ScreenUtil().setWidth(60.0),
                      width: ScreenUtil().setWidth(120.0),
                      child: Image.asset(
                        'assets/icon/NewsMessageButtonIcon.png',
                        width: ScreenUtil().setWidth(50.0),
                        height: ScreenUtil().setWidth(50.0),
                      ),
                    ),
                    onTap: () {
                      _focusNode.unfocus(); // 失去焦点
                      setState(() {
                        quickMessageListState = false;
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建消息视图
  Widget _buildMsg(entity) {
    if (entity == null || entity.position == null) {
      return Container();
    }
    if (entity.position == '2') {
      return Container(
        margin: EdgeInsets.all(ScreenUtil().setWidth(20.0)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Text(
                  entity.userName,
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: ScreenUtil().setSp(26.0),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: ScreenUtil().setWidth(10.0),
                  ),
                  padding: EdgeInsets.all(10.0),
                  decoration: BoxDecoration(
                    color: Colors.lightGreen,
                    borderRadius: BorderRadius.all(
                      Radius.circular(ScreenUtil().setWidth(8.0)),
                    ),
                  ),
                  constraints: BoxConstraints(
                    maxWidth: ScreenUtil().setWidth(400.0),
                  ),
                  child: Text(
                    entity.content ?? '',
                    overflow: TextOverflow.clip,
                    style: TextStyle(
                      fontSize: ScreenUtil().setSp(36.0),
                    ),
                  ),
                )
              ],
            ),
            Card(
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(20.0)),
              clipBehavior: Clip.hardEdge,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(20.0)),
              ),
              elevation: 0.0,
              child: Container(
                height: ScreenUtil().setWidth(80.0),
                width: ScreenUtil().setWidth(80.0),
                child: Image.network(entity.headimgurl),
              ),
            ),
          ],
        ),
      );
    } else {
      return Container(
        margin: EdgeInsets.all(
          ScreenUtil().setWidth(20.0),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Card(
              margin: EdgeInsets.only(
                right: ScreenUtil().setWidth(20.0),
              ),
              clipBehavior: Clip.hardEdge,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
                    Radius.circular(ScreenUtil().setWidth(40.0))),
              ),
              elevation: 0.0,
              child: Container(
                height: ScreenUtil().setWidth(80.0),
                width: ScreenUtil().setWidth(80.0),
                child: Image.network(entity.headimgurl),
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  entity.userName,
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: ScreenUtil().setSp(26.0),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: ScreenUtil().setWidth(10.0),
                  ),
                  padding: EdgeInsets.all(ScreenUtil().setWidth(20.0)),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(
                      ScreenUtil().setWidth(8.0),
                    )),
                  ),
                  constraints: BoxConstraints(
                    maxWidth: ScreenUtil().setWidth(400.0),
                  ),
                  child: Text(
                    entity.content ?? '',
                    overflow: TextOverflow.clip,
                    style: TextStyle(
                      fontSize: ScreenUtil().setSp(32.0),
                    ),
                  ),
                )
              ],
            ),
          ],
        ),
      );
    }
  }

  // 快速发送消息列表
  Widget _quickMessageList(title) {
    return Column(
      children: <Widget>[
        Container(
          width: ScreenUtil().setWidth(750.0),
          height: ScreenUtil().setWidth(110.0),
          alignment: Alignment.center,
          child: Text(
            title,
            style: TextStyle(
              fontSize: ScreenUtil().setSp(30.0),
              color: Colors.black87,
            ),
          ),
        ),
        Divider(height: ScreenUtil().setWidth(1.0)),
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}

/// 信息实体
class MessageEntity {
  bool own;
  String msg;

  MessageEntity(this.own, this.msg);
}
